<?php
namespace Home\Controller;

use Think\Controller;

class ApiController extends Controller 
{
	private $exceptAuth = [
		'Api' => ['login'], 
	];

	public function __construct() {
		parent::__construct();

		if (session('uid') == null &&
			!in_array(ACTION_NAME, $this->exceptAuth[CONTROLLER_NAME])) {

			\Think\Log::record('测试日志信息');
			echo json_encode(['status'=>401]);
			exit();
		}
	}

	public function newdata() {
		$field = 'data';	
		if (I('control')) {
			$field = 'control';	
			$json = htmlspecialchars_decode(I('control'));	
		} else {
			$json = htmlspecialchars_decode(I('data'));
		}
		$model = M('UserData');

		$uid = session('uid');

		if ($model->where(['user_id'=>$uid])->select()) {
			$model->where(['user_id'=>$uid])->setField($field, $json);
			$model->where(['user_id'=>$uid])->setField('last_update', date('Y-m-d h:i:s'));
		} else {
			$data['user_id'] = $uid;
			$data[$field] = $json;
			$model->add($data);
		}

	}

	public function data() {
		$model = M('UserData');
		$uid = session('uid');

		if (I('data')) {
			$data = $model->where(['user_id'=>$uid])->getField('data');
		} else {
			$data = $model->where(['user_id'=>$uid])->getField('control');
		}

		if ($data) {
			echo json_encode(['status'=>200,'data'=>$data]);
		}
		else {
			echo json_encode(['status'=>404,'data'=>null]);
		}
	}

	public function login() {
		$user = D('User');
		$user->where(['username'=>I('username')])->find();

		session(array('expire'=>3600));
		if ($user->login(I('password'))) {
			$data = ['status'=>100];
		} else {
			$data = ['status'=>110];
		}

		echo json_encode($data);
		return;

	}
}